<?php

namespace app\common\model;

use Think\Db;

/**
 * 微信类封装
 */
class Weixins extends Base
{

    
    public function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl))
        {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        return $data;
    }

    /**
     * 模拟post提交
     * $post_string 提交数组
     * $url 链接
     */
    public function dataPost($post_string, $url)
    {
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /**
     * 获取token
     */
    public function get_token()
    {
        $file = 'access_token.php';
        if (is_file($file))
        {
            $access_token = file_get_contents($file);
            $access_token = unserialize(substr($access_token, 10));
        }
        else
        {
            $access_token = ['time' => 0];
        }
        if ((time() - $access_token['time']) > 6000)
        {
            $appid                        = config('AppId');
            $appsecret                    = config('AppSecret');
            $url                          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $userinfo_json                = self::https_request($url);
            $userinfo_array               = json_decode($userinfo_json, true);
            $access_token['access_token'] = $userinfo_array['access_token'];
            $access_token['time']         = time();
            file_put_contents($file, '<?=exit;?>' . serialize($access_token));
            return $access_token['access_token'];
        }
        else
        {
            return $access_token['access_token'];
        }
    }

    /**
     * 通过code获取用户信息
     */
    public function getUserInfo($code)
    {
        $appid = config('AppId');
        $appsecret = config('AppSecret');
        //$access_token = $_COOKIE['access_token'];
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        $access_token_json = self::https_request($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        $access_token = $access_token_array['access_token'];
        $openid = $access_token_array['openid'];

        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
        $userinfo_json = self::https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json, true);
        return $userinfo_array;
    }
    
    /**
     * 通过openid获取用户信息
     */
    public function get_member_info($openid)
    {
        $access_token = self::get_token();
        $access_token_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN ";
        $access_token_json = self::https_request($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        
        return  $access_token_array;
    }

    /**
     * 生成临时二维码 获取title
     */
    public function https_post($data = null)
    {
        $access_token = self::get_token();
        $url          = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
        $curl         = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data))
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 通过ticket 获取二维码图片
     */
    public function get_ewm($ticket)
    {
        $ticket             = urldecode($ticket);
        $access_token_url   = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=$ticket";
        $access_token_json  = https_request($access_token_url);
        $access_token_array = json_decode($access_token_json, true);
        return $access_token_array;
    }



    /**
     * 发送客服消息
     */
    public function send_text($openid, $content)
    {
        $access_token = self::get_token();
        $post_string  = "{
            \"touser\":\"{$openid}\",
            \"msgtype\":\"text\",
            \"text\":
            {
                 \"content\":\"{$content}\"
            }
        }";
        $url          = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
        $rs           = self::dataPost($post_string, $url);
    }

    
    ///////////////////////////////////分享朋友圈分享朋友用
    
    public function getSignPackage()
    {
        $jsapiTicket = self::get_ticket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url       = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr  = self::createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature   = sha1($string);
        $appid       = config('AppId');
        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    public function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str   = "";
        for ($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function get_ticket()
    {
        $file        = 'jsapi_ticket.php';
        $accessToken = get_token();
        if (is_file($file))
        {
            $ticket = file_get_contents($file);
            $ticket = unserialize(substr($ticket, 10));
        }
        else
        {
            $ticket = ['time' => 0];
        }
        if ((time() - $ticket['time']) > 6000)
        {
            $url              = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}";
            $userinfo_json    = https_request($url);
            $userinfo_array   = json_decode($userinfo_json, true);
            $ticket['ticket'] = $userinfo_array['ticket'];
            $ticket['time']   = time();
            file_put_contents($file, '<?=exit;?>' . serialize($ticket));
            return $ticket['ticket'];
        }
        else
        {
            return $ticket['ticket'];
        }
    }

///////////////////////////////////分享朋友圈分享朋友用


////////////////////////////////////app支付开始    
    
    /**
     * app微信支付
     */
    public function get_prepay_id($arr)
    {
        $appid       = 'wxf305701a80fef84f'; //微信分配的公众账号ID
        $attach      = $arr['attach']; //附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据  //
        //[1 => '购买商品', 2 => '保障金']
        $body        = $arr['body'];
        $mch_id      = '1515341991';
        $partner_key = "b56f068a87846f72f8f70eb5547e67f0"; //密钥md5百姓圈
        $nonce_str   = md5(time()); //随机字符串，不长于32位。
        $notify_url = 'http://'.$_SERVER['HTTP_HOST'].'/api/index/wxcallback'; //回调
        $suiji            = mt_rand(1000, 9999);
        $out_trade_no     = $arr['out_trade_no'] . $suiji; //商户系统内部的订单号,32个字符内、可包含字母, 
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"]; //APP和网页支付提交用户端ip
        $total_fee        = $arr['fee'] * 100; //订单总金额，单位为分
        $trade_type       = 'APP';

        $opt     = [
            'appid'            => $appid,
            'attach'           => $attach,
            'body'             => $body,
            'mch_id'           => $mch_id,
            'nonce_str'        => $nonce_str,
            'notify_url'       => $notify_url,
            'out_trade_no'     => $out_trade_no,
            'spbill_create_ip' => $spbill_create_ip,
            'total_fee'        => $total_fee,
            'trade_type'       => $trade_type
        ];
        $str_tmp = '';
        foreach ($opt as $k => $v)
        {
            $str_tmp.=$k . '=' . $v . "&";
        }
        
        $str_tmp.='key=' . $partner_key;
        $sign        = strtoupper(md5($str_tmp));
        $opt['sign'] = $sign;
        $xml         = self::arrayToXml($opt);
        $rs          = self::get_contents('https://api.mch.weixin.qq.com/pay/unifiedorder', $xml);
        P($rs);
        $rs          = self::xmlToArray($rs);
        P($rs);
        $rs['time']  = time();
        $return_rs   = [
            'appid'     => $rs['appid'],
            'noncestr'  => md5(time() . md5(time())),
            'package'   => 'Sign=WXPay',
            'partnerid' => $rs['mch_id'],
            'prepayid'  => $rs['prepay_id'],
            'timestamp' => time()
        ];

        //生成签名
        $str_tmp = '';
        foreach ($return_rs as $k => $v)
        {
            $str_tmp.=$k . '=' . $v . "&";
        }
        $str_tmp.='key=' . $partner_key;
       
        $sign              = strtoupper(md5($str_tmp));
        $return_rs['sign'] = $sign;
        return $return_rs;
    }
    
    /**
     * 数组转xml
     * $arr 数组
     */
    public function arrayToXml($arr)
    {
        $xml = '<xml>';
        foreach ($arr as $key => $value)
        {
            $xml .= "<{$key}>";
//        $xml .= "<![CDATA[{$value}]]>";
            $xml .= $value;
            $xml .= "</{$key}>";
        }
        $xml .= '</xml>';

        return $xml;
    }
    
    /**
     * xml转换数组
     */
    public function xmlToArray($xml)
    {
        $xmlObj = simplexml_load_string(
            $xml, 'SimpleXMLIterator', //可迭代对象
            LIBXML_NOCDATA
        );

        $arr = [];
        $xmlObj->rewind(); //指针指向第一个元素
        while (1)
        {
            if (!is_object($xmlObj->current()))
            {
                break;
            }
            $arr[$xmlObj->key()] = $xmlObj->current()->__toString();
            $xmlObj->next(); //指向下一个元素
        }

        return $arr;
    }
    
    /**
     *模拟提交
     */
    public function get_contents($url, $data = [])
    {
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

}
